package com.sharding.demo.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author hu xu hong
 * @Date 2023/2/8 17:46
 */
@Component
public class HitManagerConfig {

    private HintManager hintManager;

    private HintManagerTTL hintManagerTTL;

    public  String getDatabaseShardingValues(){
        String shardingValue = null;
        Collection<Comparable<?>> shardingValues = HintManagerTTL.getDatabaseShardingValues();
        for (Object value : shardingValues) {
            shardingValue = String.valueOf(value);
            break;
        }
        if(shardingValue == null){
            throw new RuntimeException("无法从上下文信息中获取企业信息");
        }
        return shardingValue;
    }

    public Long getTcloudId(){
        String dbShardingValue = getDatabaseShardingValues();
        Long tcloudId = Long.valueOf(dbShardingValue);
        return tcloudId;
    }

    //初始化分库分片键
    public  void initShardingSphere(String shardValue){
        if(StringUtils.isBlank(shardValue)){
            throw new RuntimeException("分库分片键不存在");
        }
        HintManager.clear();
        HintManagerTTL.clear();
        hintManager = HintManager.getInstance();
        HintManagerUtils.setHintValue(hintManager, HintType.DATABASE_ONLY, null,shardValue);

        hintManagerTTL = HintManagerTTL.getInstance();
        hintManagerTTL.setDatabaseShardingValue(shardValue);
    }

    //删除分库分片键
    public void closeShardingSphere(){
        if(hintManager!=null){
            hintManager.close();
            hintManager = null;
        }
        if(hintManagerTTL!=null){
            hintManagerTTL.close();
            hintManagerTTL = null;
        }
    }
}
